
import { RewardOrderInfo } from "../model/RewardOrderInfo";
import { UserEntity } from "./UserEntity";
import { UserManager } from "./UserManager";

import { LogicServer } from "../../LogicServer";
import { EnumCacheGroup } from "../../../../common/enum/EnumCacheGroup";
import { GameBetOrderInfo } from "../../../../common/model/GameBetOrderInfo";
import { UserData } from "../../../../common/model/UserData";
import { CacheComponent } from "../../../../framework/service/Components/CacheComponent";


export class RewardManager {
    private static _instance: RewardManager;

    public static get inst(): RewardManager {
        if (!this._instance) {
            this._instance = new RewardManager();
        }
        return this._instance;

    }


    private _rewardOrders: RewardOrderInfo[] = [];


    public addBetRewardOrder(order: GameBetOrderInfo): void {

        if (order.win <= 0) {
            return;
        }
        
        const gameRewardOrder: RewardOrderInfo = new RewardOrderInfo();
        //gameRewardOrder.rewardType = EnumValType.coin;
        gameRewardOrder.toUserId = order.userid;
        gameRewardOrder.value = order.win;
        this._rewardOrders.push(gameRewardOrder);

    }


    public async doBetReward(order: GameBetOrderInfo): Promise<void> {
        
        const user: UserEntity = UserManager.inst.getUser(order.userid);

        if(user){
            user.coin = user.data.gameData.coins += order.win;
        }
        else{
            //**离线用户需要从数据库里面查 */
            const cacheComp: CacheComponent = <CacheComponent>LogicServer.entity.getComponent(CacheComponent);

            const username: string = await cacheComp.get(EnumCacheGroup.USERID_TO_USERNAME, order.userid);


            const userdata: UserData = await cacheComp.get(EnumCacheGroup.USER_DATA, username);

            userdata.gameData.coins += order.win;
            await cacheComp.set(EnumCacheGroup.USER_DATA,username,userdata);

        }
    }
    public update(dt: number): void {

    }
}   